package com.example.xmpic.ui.activity.bind;

import com.example.xmpic.R;
import com.example.xmpic.databinding.ActivityBindLanBinding;
import com.example.common.base.BasePresentActivity;
import com.example.common.base.OnCallBackToEdit;
import com.example.common.utils.LiveDataBus;
import com.example.common.view.refresh.CustomRefreshView;
import com.example.xmpic.support.FunDevicePassword;
import com.example.xmpic.support.FunError;
import com.example.xmpic.support.FunSupport;
import com.example.xmpic.support.OnFunDeviceListener;
import com.example.xmpic.support.OnFunDeviceOptListener;
import com.example.xmpic.support.models.FunDevice;
import com.example.xmpic.support.models.FunLoginType;
import com.example.xmpic.mvp.contract.CameraIncreaseContract;
import com.example.xmpic.mvp.present.CameraIncreasePresenter;
import com.example.xmpic.ui.adapter.LocalNetIPCAdapter;
import com.example.xmpic.view.InputPwdDialog;
import com.lib.FunSDK;
import com.lib.sdk.struct.H264_DVR_FILE_DATA;

import java.util.ArrayList;
import java.util.List;

/**
 *  搜索显示同一个局域网内的设备列表
 * 1. 切换访问模式为本地访问  - FunSDK.SysInitLocal()
 * 2. 注册设备列表更新监听  - FunSupport.registerOnFunDeviceListener()
 * 3. 搜索局域网内的设备 - FunSDK.DevSearchDevice()
 * 4. 搜索结果通过监听返回  - onLanDeviceListChanged()/标识设备列表变化了,界面可以刷新了
 * 5. 退出并注销监听
 */
public class CameraConfigInLanActivity extends BasePresentActivity<CameraIncreasePresenter, ActivityBindLanBinding> implements OnFunDeviceListener,
		OnFunDeviceOptListener, CameraIncreaseContract.IView {

	private LocalNetIPCAdapter mAdapter = null;
	private List<FunDevice> mLanDeviceList;
	private FunDevice funDevice;
	private int mPosition;
	private boolean isAddedSuccessfully = true;

	@Override
	protected int getLayoutId() {
		return R.layout.activity_bind_lan;
	}

	@Override
	protected void initPresent() {
		super.initPresent();
		mPresent = new CameraIncreasePresenter(mContext);
	}

	@Override
	protected void initView() {
		super.initView();
		mLanDeviceList = new ArrayList<>();
		mAdapter = new LocalNetIPCAdapter(mContext);
		mDBind.crLocalList.setRefreshing(false);
		mDBind.crLocalList.setAdapter(mAdapter);
	}

	@Override
	protected void initData() {
		super.initData();
		// 刷新设备列表
		refreshLanDeviceList();
		// Demo，如果是进入设备列表就切换到本地模式,退出时切换回NET模式
		FunSupport.getInstance().setLoginType(FunLoginType.LOGIN_BY_LOCAL);
		// 监听设备类事件
		FunSupport.getInstance().registerOnFunDeviceListener(this);
		// 注册设备操作回调
		FunSupport.getInstance().registerOnFunDeviceOptListener(this);
		// 打开之后进行一次搜索
		requestToGetLanDeviceList();
	}

	@Override
	protected void initDataBus() {
		super.initDataBus();
		LiveDataBus.get().with(LocalNetIPCAdapter.ITEM_CLICK_IPC, Integer.class).observe(this, integer -> {
			this.mPosition = integer;
			funDevice = mLanDeviceList.get(integer);
			if (null != funDevice && isAddedSuccessfully) {
				if(!funDevice.hasLogin() || !funDevice.hasConnected()) {
					FunSupport.getInstance().requestDeviceLogin(funDevice);
				}else {
					showProgressDialog();
					isAddedSuccessfully = false;
					mPresent.refreshModifyUserInfo(funDevice.getDevSn(),funDevice.getDevName());
				}
			}else {
				showToast(R.string.please_not_operation_so_quickly);
			}
		});
	}

	@Override
	protected void initListener() {
		super.initListener();
		mDBind.ivLocalNetBack.setOnClickListener(view -> finish());
		mDBind.crLocalList.setOnLoadListener(new CustomRefreshView.OnLoadListener() {
			@Override
			public void onRefresh() {
				// 刷新设备列表
				requestToGetLanDeviceList();
				mDBind.crLocalList.complete();
			}

			@Override
			public void onLoadMore() {

			}
		});
	}

	private void requestToGetLanDeviceList() {
		if (!FunSupport.getInstance().requestLanDeviceList() ) {
			showToast(getString(R.string.guide_message_error_call));
		} else {
			showProgressDialog();
		}
	}
	
	private void refreshLanDeviceList() {
		mLanDeviceList.clear();
		mLanDeviceList.addAll(FunSupport.getInstance().getLanDeviceList());
		if (mLanDeviceList.size()>0){
			FunSupport.getInstance().requestAllLanDeviceStatus();
			mAdapter.setLists(mLanDeviceList);
			dismissProgressDialog();
		}else {
			mAdapter.setLists(null);
			mDBind.crLocalList.setEmptyView("", R.mipmap.device_history_empty);
		}
	}

	/**
	 * 以下函数实现来自OnFunDeviceListener()，监听设备列表变化
	 */
	@Override
	public void onDeviceListChanged() {
	}

	@Override
	public void onDeviceStatusChanged(final FunDevice funDevice) {
		mAdapter.notifyDataSetChanged();
	}
	
	@Override
	public void onDeviceAddedSuccess() {
		
	}


	@Override
	public void onDeviceAddedFailed(Integer errCode) {
		
	}


	@Override
	public void onDeviceRemovedSuccess() {
		
	}


	@Override
	public void onDeviceRemovedFailed(Integer errCode) {
		
	}
	
	@Override
	public void onAPDeviceListChanged() {
		
	}
	
	@Override
	public void onLanDeviceListChanged() {
		refreshLanDeviceList();
	}

	@Override
	public void onDeviceLoginSuccess(FunDevice funDevice) {
		if (funDevice != null && funDevice == mLanDeviceList.get(mPosition)){
			showProgressDialog();
			mPresent.refreshModifyUserInfo(funDevice.getDevSn(),funDevice.getDevName());
		}
	}

	@Override
	public void onDeviceLoginFailed(FunDevice funDevice, Integer errCode) {
		// 如果账号密码不正确,那么需要提示用户,输入密码重新登录
		dismissProgressDialog();
		if (errCode == FunError.EE_DVR_PASSWORD_NOT_VALID) {
			showInputPasswordDialog();
		}
	}

	@Override
	public void onDeviceGetConfigSuccess(FunDevice funDevice, String configName, int nSeq) {

	}

	@Override
	public void onDeviceGetConfigFailed(FunDevice funDevice, Integer errCode) {

	}

	@Override
	public void onDeviceSetConfigSuccess(FunDevice funDevice, String configName) {

	}

	@Override
	public void onDeviceSetConfigFailed(FunDevice funDevice, String configName, Integer errCode) {

	}

	@Override
	public void onDeviceChangeInfoSuccess(FunDevice funDevice) {

	}

	@Override
	public void onDeviceChangeInfoFailed(FunDevice funDevice, Integer errCode) {

	}

	@Override
	public void onDeviceOptionSuccess(FunDevice funDevice, String option) {

	}

	@Override
	public void onDeviceOptionFailed(FunDevice funDevice, String option, Integer errCode) {

	}

	@Override
	public void onDeviceFileListChanged(FunDevice funDevice) {

	}

	@Override
	public void onDeviceFileListChanged(FunDevice funDevice, H264_DVR_FILE_DATA[] datas) {

	}

	@Override
	public void onDeviceFileListGetFailed(FunDevice funDevice) {

	}

	/**
	 * 显示输入设备密码对话框
	 */
	private void showInputPasswordDialog() {
		InputPwdDialog mDialog = new InputPwdDialog(mContext, new OnCallBackToEdit() {
			@Override
			public void onConfirm(String name) {
				onDeviceSaveNativePws(name);
				if (null != funDevice) {
					FunSupport.getInstance().requestDeviceLogin(funDevice);
				}
			}

			@Override
			public void onCancel() {
			}
		});
		mDialog.setTitleAndButton(getString(R.string.device_login_input_password), getString(R.string.ok));
		mDialog.show();
	}


	public void onDeviceSaveNativePws(String NativeLoginPsw) {
		FunDevicePassword.getInstance().saveDevicePassword(funDevice.getDevSn(),
				NativeLoginPsw);
		// 库函数方式本地保存密码
		if (FunSupport.getInstance().getSaveNativePassword()) {
			FunSDK.DevSetLocalPwd(funDevice.getDevSn(), "admin", NativeLoginPsw);
			// 如果设置了使用本地保存密码，则将密码保存到本地文件
		}
	}

	@Override
	public void hasExits() {
		dismissProgressDialog();
		showToast(getString(R.string.device_has_been_exist));
	}

	@Override
	public void showToastMsg(String msg) {
		dismissProgressDialog();
		isAddedSuccessfully = true;
		showToast(msg);
	}

	@Override
	public void bindSuccess() {
		isAddedSuccessfully = true;
		dismissProgressDialog();
		showToast(getString(R.string.success_add));
		finish();
	}

	@Override
	public void deleteSuccess() {

	}

	@Override
	protected void onDestroy() {
		// 注销设备事件监听
		FunSupport.getInstance().removeOnFunDeviceListener(this);
		FunSupport.getInstance().removeOnFunDeviceOptListener(this);
		super.onDestroy();
	}
}
